//
//  moodViewController.m
//  NewMusic
//
//  Created by dllo on 15/11/24.
//  Copyright © 2015年 Going. All rights reserved.
//

#import "moodViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "CustomerNetworking.h"
#import "moodHeaderView.h"
#import "ListenDataSongsModel.h"
#import "PlayerViewController.h"
#import "MusicType.h"
#import "SongsAuditionListModel.h"
@interface moodViewController ()<UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLGeocoder *geocoder;
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, retain) moodHeaderView *headerView;
@property (nonatomic, copy) NSString *weatherString;
@property (nonatomic, copy) NSString *loadString;
@property (nonatomic, retain) NSMutableArray *dataArray;
@end

@implementation moodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"本地天气";
    self.loadString = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.1.1.2015110616", @"欢快"];
    self.dataArray = [NSMutableArray array];
    self.geocoder = [[CLGeocoder alloc] init];
    [self createButton];
    [self createTableView];
    [self loadNewSongsData];
    [self requireLocation];
}
- (void)createButton {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
}
- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)requireLocation {
    self.locationManager = [[CLLocationManager alloc]init];
    //设置定位精度
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //开始时定位
    [_locationManager requestAlwaysAuthorization];
    [_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [_locationManager stopUpdatingLocation];
    NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans", nil] forKey:@"AppleLanguages"];
    NSString *str = [NSString stringWithFormat:@"http://v.juhe.cn/weather/index?format=2&cityname=%@&key= f393daebc4db79a9cfd67843a1543d4f", @"大连"];
    self.urlString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [_geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error && [placemarks count] > 0) {
             NSDictionary *dicte = [[placemarks objectAtIndex:0] addressDictionary];
            NSString *str = [NSString stringWithFormat:@"http://v.juhe.cn/weather/index?format=2&cityname=%@&key= f393daebc4db79a9cfd67843a1543d4f", [dicte valueForKey:@"City"]];
            self.urlString = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        }
        [self loadData];
        [[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
    }];
}
- (void) loadData {
[CustomerNetworking customerConnectWithURL:self.urlString andParameters:nil andBlock:^(id response) {
    self.weatherString = [[[response valueForKey:@"result"] valueForKey:@"today"] valueForKey:@"weather"];
    self.headerView.weatherString = _weatherString;
    if ([_weatherString containsString:@"阴"]) {
        self.loadString = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.1.1.2015110616", @"阴"];
    }else if ([_weatherString containsString:@"雨"]) {
        self.loadString = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.1.1.2015110616", @"雨"];
    }else if ([_weatherString containsString:@"雪"]) {
        self.loadString = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.1.1.2015110616", @"浪漫"];
    }else {
        self.loadString = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?q=%@&page=1&size=50&app=ttpod&v=v8.1.1.2015110616", @"欢快"];
    }
    [self.dataArray removeAllObjects];
    [self loadNewSongsData];
}];
    
}
- (void)loadNewSongsData {
    self.loadString = [self.loadString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[CustomerNetworking customerConnectWithURL:self.loadString andParameters:nil andBlock:^(id response) {
    NSArray *array = [response valueForKey:@"data"];
    for (NSDictionary *dic in array) {
        ListenDataSongsModel *model = [[ListenDataSongsModel alloc]initWithDictionary:dic];
        [self.dataArray addObject:model];
        [model release];
    }
    [self.tableView reloadData];
}];
}
- (void)createTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 123) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    //头视图
    self.headerView = [[moodHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 170)];
    self.tableView.tableHeaderView = _headerView;
    [self.view addSubview:_tableView];
    [_headerView release];
    [_tableView release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentify = @"moodCellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentify];
    }
    if (_dataArray.count != 0) {
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.text = [_dataArray[indexPath.row] valueForKey:@"name"];
        cell.detailTextLabel.textColor = [UIColor whiteColor];
        cell.detailTextLabel.text = [_dataArray[indexPath.row] valueForKey:@"singerName"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count ? _dataArray.count : 0;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayerViewController *player = [PlayerViewController sharePlayerViewController];
    NSMutableArray *arr = [NSMutableArray array];
    for (NSInteger i = 0; i < self.dataArray.count; i++)
    {
        ListenDataSongsModel *song = self.dataArray[i];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:song.albumName forKey:@"album"];// 专辑
        [dic setValue:song.name forKey:@"name"]; // 歌名
        NSMutableArray *array = [NSMutableArray array];
        for (SongsAuditionListModel *model in song.auditionList) {
            MusicType *type = [[MusicType alloc]init];
            type.url = model.urlString;
            type.typeDescription = model.typeDescription;
            [array addObject:type];
        }
        [dic setValue:array forKey:@"music"]; // 歌曲,model用musicType
        [dic setValue:song.singerName forKey:@"songerName"];// 歌手名
        [dic setValue:song.albumId forKey:@"id"]; // id
        [arr addObject:dic];
    }
    player.musicArr = arr;
    [player MusicStart:indexPath.row];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
